package com.flyduck.security.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p></p>
 *
 * @author flyduck 2021/7/7
 * @version V1.0
 * @modificationHistory=========================逻辑或功能性重大变更记录
 * @modify by user: flyduck 2021/7/7
 * @modify by reason:{方法名}:{原因}
 **/
public class JwtTokenUtil {
    public final static String TOKEN_HEADER = "Authorization";
    public final static String TOKEN_PREFIX = "Bearer ";

    private final static long TOKEN_EXPIRATION = 24 * 60 * 60 * 1000;
    private final static String APP_SECRET_KEY = "fly_duck";
    private final static String CLAIM_AUTHORITIES_KEY = "authorities";
    private final static String CLAIM_ID_KEY = "userId";

    public String createToken(String userName) {
        String token = Jwts.builder().setSubject(userName)
                .setExpiration(new Date(System.currentTimeMillis() + TOKEN_EXPIRATION))
                .signWith(SignatureAlgorithm.HS256, APP_SECRET_KEY).compact();
        return token;
    }

    public static String createToken(String userName, List<String> authorities) {
        String token = Jwts.builder().setSubject(userName)
                .claim(CLAIM_AUTHORITIES_KEY, authorities)
                .setExpiration(new Date(System.currentTimeMillis() + TOKEN_EXPIRATION))
                .signWith(SignatureAlgorithm.HS256, APP_SECRET_KEY).compact();
        return token;
    }

    public static String createToken(String userId, String userName, List<String> authorities) {
        String token = Jwts.builder().setSubject(userName)
                .claim(CLAIM_ID_KEY, userId)
                .claim(CLAIM_AUTHORITIES_KEY, authorities)
                .setExpiration(new Date(System.currentTimeMillis() + TOKEN_EXPIRATION))
                .signWith(SignatureAlgorithm.HS256, APP_SECRET_KEY).compact();
        return token;
    }

    public static String getUserName(String token) {
        String userName = Jwts.parser().setSigningKey(APP_SECRET_KEY).parseClaimsJws(token).getBody().getSubject();
        return userName;
    }

    public static List<String> getAuthorities(String token) {
        Claims claims = Jwts.parser().setSigningKey(APP_SECRET_KEY).parseClaimsJws(token).getBody();
        List<String> authorities = new ArrayList<>();
        Object claimAuthorities = claims.get(CLAIM_AUTHORITIES_KEY);
        if (claimAuthorities != null) {
            authorities = (List<String>)claimAuthorities;
        }
        return authorities;
    }

    public static boolean isExpiration(String token){
        Claims claims = Jwts.parser().setSigningKey(APP_SECRET_KEY).parseClaimsJws(token).getBody();
        return claims.getExpiration().before(new Date());
    }
}
